<template>
  <!-- 系统目录 西成药品 -->
  <div class="MedicenCata">

    <div class="dialog">

      <!--患者选择-->
      <el-dialog
          title="患者选择"
          :close-on-click-modal="false"
          :visible.sync="patientDialogVisible"
          width="50%"
          class="patient-dialog"
      >
        <!-- 患者表格 -->
        <el-table
            :data="patientTabelData"
            border
            highlight-current-row
            @current-change="handleClickRow"
            style="width: 100%"
            height="500px"
        >
          <el-table-column v-for="(col, inx) in tableRows6" :key="inx" :type="col.type" :prop="col.prop"
                           :label="col.name" :render-header="labelHead" align="center"
                           :min-width="getColumnWidth(col.label,col.prop,patientTabelData)">
            <template #default="{ row }">
              {{ safeGetMappedValue(col, row) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="custom-dialog-footer">
          <el-button @click="patientDialogVisible = false" size="mini">取消</el-button>
          <el-button type="primary" size="mini" :loading="loading" @click="handleConditionQuery">确定</el-button>
        </div>
      </el-dialog>

      <!--西药退费数据-->
      <el-dialog
          title="西药退费详情"
          :close-on-click-modal="false"
          :visible.sync="westReturnMoneyDialogVisible"
          width="90%"
          class="patient-dialog"
      >
        <div class="dual-table-container">
          <!-- Left Table -->
          <div class="table-wrapper">
            <el-table
                ref="leftTable"
                :data="tableData6"
                border
                highlight-current-row
                @row-click="handleLeftTableRowClick"
                style="width: 100%; height: 100%"
            >
              <el-table-column
                  v-for="(col, inx) in tableRows7"
                  :key="inx"
                  :type="col.type"
                  :prop="col.prop"
                  :label="col.name"
                  align="center"
                  :render-header="labelHead"
                  :min-width="getColumnWidth(col.label, col.prop, tableData6)"
              >
                <template #default="{ row }">
                  {{ safeGetMappedValue(col, row) }}
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- Right Table -->
          <div class="table-wrapper">
            <el-table
                ref="rightTable"
                :data="tableData9"
                border
                highlight-current-row
                style="width: 100%; height: 100%"
                @selection-change="handleWestRefundRelevance"
            >
              <el-table-column
                  type="selection"
                  width="55"
                  align="center"
              ></el-table-column>
              <el-table-column
                  v-for="(col, inx) in tableRows10"
                  :key="inx"
                  :type="col.type"
                  :prop="col.prop"
                  :label="col.name"
                  align="center"
                  :min-width="getColumnWidth(col.label, col.prop, tableData9)"
              >
                <template #default="{ row }">
                  {{ safeGetMappedValue(col, row) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <span slot="footer" class="dialog-footer no-line">
    <el-button @click="westReturnMoneyDialogVisible = false" size="mini">取消</el-button>
    <el-button type="primary" @click="handleWestRefund" size="mini">继续退款</el-button>
  </span>
      </el-dialog>

      <!--中药退费数据-->
      <el-dialog
          title="中药退费详情"
          :close-on-click-modal="false"
          :visible.sync="chinaReturnMoneyDialogVisible"
          width="90%"
          class="patient-dialog"
      >
        <div class="dual-table-container">
          <!-- Left Table (中药主表) -->
          <div class="table-wrapper">
            <el-table
                ref="chinaLeftTable"
                :data="tableData8"
                border
                highlight-current-row
                style="width: 100%; height: 100%"
            >
              <el-table-column
                  v-for="(col, inx) in tableRows9"
                  :key="inx"
                  :type="col.type"
                  :prop="col.prop"
                  :label="col.name"
                  align="center"
                  :render-header="labelHead"
                  :min-width="getColumnWidth(col.label, col.prop, tableData8)"
              >
                <template #default="{ row }">
                  {{ safeGetMappedValue(col, row) }}
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- Right Table (中药明细/关联数据) -->
          <div class="table-wrapper">
            <el-table
                ref="chinaRightTable"
                :data="tableData10"
                border
                highlight-current-row
                style="width: 100%; height: 100%"
                @selection-change="handleChinaRefundRelevance"
            >
              <el-table-column
                  type="selection"
                  width="55"
                  align="center"
              ></el-table-column>
              <el-table-column
                  v-for="(col, inx) in tableRows10"
                  :key="inx"
                  :type="col.type"
                  :prop="col.prop"
                  :label="col.name"
                  align="center"
                  :min-width="getColumnWidth(col.label, col.prop, tableData10)"
              >
                <template #default="{ row }">
                  {{ safeGetMappedValue(col, row) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <span slot="footer" class="dialog-footer no-line">
    <el-button @click="chinaReturnMoneyDialogVisible = false" size="mini">取消</el-button>
    <el-button type="primary" @click="handleChinaRefund" size="mini">继续退款</el-button>
  </span>
      </el-dialog>

      <!--处置退费数据-->
      <el-dialog
          title="处置退费详情"
          :close-on-click-modal="false"
          :visible.sync="dispositionReturnMoneyDialogVisible"
          width="70%"
          height="50vh"
          class="patient-dialog"
      >
        <el-table
            ref="rightTable"
            :data="tableData7"
            border
            height="100%"
            highlight-current-row
            style="width: 100%">
          <el-table-column v-for="(col, inx) in tableRows8" :key="inx" :type="col.type" :prop="col.prop"
                           :label="col.name" align="center" :render-header="labelHead"
                           :min-width="getColumnWidth(col.label,col.prop,tableData7)">
            <template #default="{ row }">
              {{ safeGetMappedValue(col, row) }}
            </template>
          </el-table-column>
          <el-table-column
              label="操作"
              width="200"
              align="center"
              fixed="right"
          >
            <template #default="{ row }">
              <el-button
                  :disabled="row.chargeStatus === 2 || row.chargeStatus === 3"
                  type="warning"
                  size="mini"
                  @click="handleDispositionRefund(row)"
              >申请退款
              </el-button>
              <el-button
                  :disabled="row.chargeStatus !== 2"
                  type="primary"
                  size="mini"
                  @click="handleDispositionConfirmRefund(row)"
              >确认退款
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer no-line">
    <el-button @click="dispositionReturnMoneyDialogVisible = false" size="mini">取消</el-button>
  </span>
      </el-dialog>

      <!--收费详情-->
      <el-dialog
          title="收费详情"
          :close-on-click-modal="false"
          :visible.sync="showChargeDtailDialog"
          width="70%"
          height="50vh"
          class="patient-dialog"
      >

        <div class="medical-system-container">
          <!-- 1. 主表格区域 -->
          <div class="table-main-container" :class="{'with-drawer': showDetails}">
            <!-- 左侧主表格 -->
            <div class="table-left">
              <el-table
                  ref="rightTable"
                  :data="tableData2"
                  border
                  height="100%"
                  @row-click="handleLeftTableRowClick"
                  style="width: 100%">
                <el-table-column v-for="(col, inx) in tableRows2" :key="inx" :type="col.type" :prop="col.prop"
                                 :label="col.name" align="center" :render-header="labelHead"
                                 :min-width="getColumnWidth(col.label,col.prop,tableData2)">
                  <template #default="{ row }">
                    {{ safeGetMappedValue(col, row) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 右侧抽屉式表格 -->
            <div class="table-drawer" :class="{'open': showPrescriptionDetails}">
              <div class="drawer-content">
                <el-table
                    :key="tableKey"
                    ref="rightTable"
                    :data="currentTableData"
                    border
                    height="100%"
                    show-summary
                    :summary-method="currentSummaryMethod"
                    style="width: 100%">

                  <!-- 动态列配置 -->
                  <el-table-column
                      v-for="(col, index) in currentTableRows"
                      :key="index"
                      :type="col.type"
                      :prop="col.prop"
                      :label="col.name"
                      align="center"
                      :width="col.prop === 'drugName' ? '300px' : col.prop === 'drugSpec' ? '300px' : '200px'"
                  >
                    <template #default="{ row }">
                      {{ safeGetMappedValue(col, row) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-checkbox v-model="showPrescriptionDetails" style="margin-right: 10px">
                显示处方明细
          </el-checkbox>
			    <el-button @click="handleClosePds" type="warning" size="mini">取消</el-button>
			  </span>

      </el-dialog>

      <!--部分零退-->
      <el-dialog
          :close-on-click-modal="false"
          :title="refundTitel"
          :visible.sync="portionRefundDialogVisible"
          width="20%"
          @close="handleCloseRefund">

        <el-form size="mini" label-width="100px" :model="refundForm" ref="refundForm">
          <el-row>
            <el-col :span="24">
              <el-form-item
                  label="挂账金额:"
                  prop="bebtAmt"
              >
                <el-input
                    type="number"
                    style="width: 60%"
                    v-model.number="refundForm.bebtAmt"
                    placeholder="请输入退费金额"
                ></el-input>
              </el-form-item>
              <el-form-item label="现金金额:" prop="cashAmt">
                <el-input
                    type="number"
                    min="1"
                    step="1"
                    style="width: 60%"
                    v-model.number="refundForm.cashAmt"
                    placeholder="请输入退费数量"
                ></el-input>
              </el-form-item>

              <el-form-item label="网络支付金额:" prop="type">
                <el-input
                    type="number"
                    min="1"
                    step="1"
                    style="width: 60%"
                    v-model.number="refundForm.groupAmt"
                    placeholder="请输入退费数量"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <span slot="footer" class="dialog-footer no-line">
    <el-button type="primary" @click="handleConfirmRefund" size="mini">确定</el-button>
    <el-button @click="handleCloseRefund" size="mini">取消</el-button>
  </span>
      </el-dialog>

    </div>
    
    <el-tabs type="border-card">
      <el-tab-pane label="患者信息">
        <el-form :model="queryConditionForm" label-width="80px" size="mini" class="responsive-form">
          <el-row :gutter="10" class="form-row">
            <!-- 健康ID -->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="3">
              <el-form-item label="健康ID:">
                <el-input
                    v-model="queryConditionForm.patId"
                    placeholder="请输入"
                    :disabled="isInputDisabled"
                    @keyup.enter.native="handleSearch"
                ></el-input>
              </el-form-item>
            </el-col>

            <!-- 时段筛选 -->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="3">
              <el-form-item label="时段筛选:">
                <el-select placeholder="请选择" v-model="queryConditionForm.timeFrame" @change="handleTimeChange">
                  <el-option
                      v-for="item in timeOption"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 开始时间 -->
            <el-col :xs="24" :sm="24" :md="16" :lg="12" :xl="6">
              <el-form-item label="时段:">
                <div style="display: flex; align-items: center;">
                  <el-date-picker
                      style="width: 180px"
                      v-model="queryConditionForm.timeFrameArr[0]"
                      type="datetime"
                      placeholder="开始时间"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      format="yyyy-MM-dd HH:mm:ss"
                      :picker-options="pickerOptionsStart"
                      @change="handleConditionQuery"
                  ></el-date-picker>
                  <span style="margin: 0 5px;">-</span>
                  <el-date-picker
                      style="width: 180px"
                      v-model="queryConditionForm.timeFrameArr[1]"
                      type="datetime"
                      placeholder="结束时间"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      format="yyyy-MM-dd HH:mm:ss"
                      :picker-options="pickerOptionsEnd"
                      @change="handleConditionQuery"
                  ></el-date-picker>
                </div>
              </el-form-item>
            </el-col>

            <!-- 单据查询 -->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="3">
              <el-form-item label="单据查询:">
                <el-input
                    v-model="queryConditionForm.docNum"
                    placeholder="请输入"
                    @keyup.enter.native="handleConditionQuery"
                ></el-input>
              </el-form-item>
            </el-col>

            <!-- 病人类型 -->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="3">
              <el-form-item label="病人类型:">
                <el-select v-model="queryConditionForm.patientType" clearable filterable placeholder="请选择" @change="handleConditionQuery">
                  <el-option
                      v-for="item in prhTypeOption"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 支付方式 -->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="3">
              <el-form-item label="支付方式:">
                <el-select v-model="queryConditionForm.opeWay" clearable placeholder="请选择" @change="handleConditionQuery">
                  <el-option
                      v-for="item in opeWayOption"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div class="medical-system-container">
      <!-- 1. 主表格区域 -->
      <div class="table-main-container" :class="{'with-drawer': showDetails}">
        <!-- 左侧主表格 -->
        <div class="table-left">
          <el-table
              :data="tableData1"
              border
              height="100%"
              show-summary
              :summary-method="getSummaries"
              @row-click="handleCurrentRow"
              @row-dblclick="handleDbShowChargeDetail"
              highlight-current-row
          >
            <el-table-column v-for="(col, inx) in tableRows1" :key="inx" :type="col.type" :prop="col.prop"
                             :label="col.name" align="center" :render-header="labelHead"
                             :min-width="getColumnWidth(col.label,col.prop,tableData1)">
              <template #default="{ row }">
                <!-- 特殊处理nuyState列 -->
                <template v-if="col.prop === 'nuyState'">
                  <el-tag :type="getNuyStateTagType(row.nuyState)"
                          size="small"
                          effect="light"
                          :class="'nuy-state-tag nuy-state-' + row.nuyState">
                    {{ getNuyStateLabel(row.nuyState) }}
                  </el-tag>
                </template>
                <!-- 其他列保持原样 -->
                <template v-else>
                  {{ safeGetMappedValue(col, row) }}
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 右侧抽屉式表格 -->
        <div class="table-drawer" :class="{'open': showDetails}">
          <div class="drawer-content">
            <el-table
                ref="rightTable"
                :data="tableData2"
                border
                height="100%"
                show-summary
                @current-change="currentDetailRefund"
                highlight-current-row
                :summary-method="getSummaries2"
                style="width: auto">
              <el-table-column v-for="(col, inx) in tableRows2" :key="inx" :type="col.type" :prop="col.prop"
                               :label="col.name" align="center" :render-header="labelHead"
                               :min-width="getColumnWidth(col.label,col.prop,tableData2)">
                <template #default="{ row }">
                  {{ safeGetMappedValue(col, row) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 2. 底部控制表单（严格保持在底部） -->
      <div class="bottom-control-form">
        <div class="button-group">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageNum"
              :page-sizes="[8, 16, 24]"
              :page-size="pageSize"
              :total="totalSize"
              layout="total, sizes, prev, pager, next, jumper"
              background>
          </el-pagination>
          <!--           前三个按钮紧挨着-->
          <div class="primary-actions">
                        <el-button type="primary" size="small" @click="handleOpenFinalReport">结班</el-button>
          </div>

          <!-- 操作按钮组  -->
          <div class="action-buttons">
            <!--            <el-button type="warning" size="small" @click="handleEditCurrentCharge">支付订单</el-button>-->
            <!--            <el-button type="danger" size="small" @click="handleFullRefund">整单退费</el-button>-->
            <el-button type="success" size="small" @click="handlePortionRefund"
                       :disabled="currentRowData.nuyState === 1 || currentRowData.nuyState === 2">部分零退
            </el-button>
            <el-button type="success" size="small" @click="printChargeList">打印</el-button>
            <!--            <el-button type="success" size="small" @click="handleSettleAccounts">发票补打</el-button>-->
            <el-button type="success" size="small" @click="handleDbShowChargeDetail(currentRowData)">查看</el-button>
            <!--            <el-button type="success" size="small" @click="handleSettleAccounts">导出</el-button>
                        <el-button type="success" size="small" @click="handleSettleAccounts">打印</el-button>-->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import {
  addContractUnit,
  addDocphr,
  dict,
  editContractUnit,
  getArea,
  getContractUnit,
  getContuntList,
  getDeptList,
  getDoctorList
} from "@/api/reservation/reservation";
import AddType from './reservationAddType.js'
import {pinyin} from "pinyin-pro";
import {getChargingPrice} from "@/api/cosrute/Cosrute";
import {addOnCredit, editOnCredit, getOnCreditById, getOnCreditList} from "@/api/reservation/outpatientCharge";
import {
  getChinaPrescription,
  getDoctordispose,
  getMedicationFrequency,
  getWestPrescription
} from "@/api/reservation/outpatientPhysician";
import {getDosaUnt, getMedicationWay} from "@/api/MedicenCata";
import {
  fullRefund,
  getChargeDetail,
  getChargeList,
  getDoctordisposeOneById,
  getDrxMainRefundList, getDtcmRxMainRefundList,
  portionRefundByDetail,
  refundDoctordispose, westRefundRelevance
} from "@/api/reservation/outpatientChargeList";
import dayjs from "dayjs";
import printUtil from "@/untils/printUtil";
import JsBarcode from "jsbarcode";
import {chargeListRegistrationSlip} from "@/assets/printTemplateConfig/chargeListRegistrationSlip";
import {withLoading} from "@/untils/loading";
import {readIdCard} from "@/untils/idCardReader";

export default {
  components: {},
  data() {

    return {
      pickerOptionsStart: {
        // 允许选择任何时间（包括过去时间）
        disabledDate: () => false, // 不禁用任何日期
      },
      pickerOptionsEnd: {
        disabledDate: (time) => {
          // 如果选择了开始时间，则结束时间不能早于它
          if (this.queryConditionForm.timeFrameArr?.[0]) {
            return dayjs(time).isBefore(dayjs(this.queryConditionForm.timeFrameArr[0]));
          }
          return false;
        }
      },

      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = dayjs();
            const start = end.subtract(1, 'week');
            picker.$emit('pick', [
              start.format('YYYY-MM-DD HH:mm:ss'),
              end.format('YYYY-MM-DD HH:mm:ss')
            ])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = dayjs();
            const start = end.subtract(1, 'month');
            picker.$emit('pick', [
              start.format('YYYY-MM-DD HH:mm:ss'),
              end.format('YYYY-MM-DD HH:mm:ss')
            ])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = dayjs();
            const start = end.subtract(3, 'month');
            picker.$emit('pick', [
              start.format('YYYY-MM-DD HH:mm:ss'),
              end.format('YYYY-MM-DD HH:mm:ss')
            ])
          }
        }, {
          text: '今天',
          onClick(picker) {
            const start = dayjs().startOf('day');
            const end = dayjs().endOf('day');
            picker.$emit('pick', [
              start.format('YYYY-MM-DD HH:mm:ss'),
              end.format('YYYY-MM-DD HH:mm:ss')
            ])
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const start = dayjs().subtract(1, 'day').startOf('day');
            const end = dayjs().subtract(1, 'day').endOf('day');
            picker.$emit('pick', [
              start.format('YYYY-MM-DD HH:mm:ss'),
              end.format('YYYY-MM-DD HH:mm:ss')
            ])
          }
        }]
      },

      pageNum: 1,
      pageSize: 10,
      totalSize: 10,

      //控制变量
      showDetails: true,//表格明细
      tableKey: 1,
      showPrescriptionDetails: true,//处方表格明细
      patientDialogVisible: false,//患者选择弹窗
      westReturnMoneyDialogVisible: false,//西药退费
      chinaReturnMoneyDialogVisible: false,//中药退费
      dispositionReturnMoneyDialogVisible: false,//处置退费
      loading: false,//加载圈
      isInputDisabled: false,//置灰健康ID
      celerityFilingDialogVisible: false,//快速建档弹窗
      settleAccountsDialogVisible: false,//门诊支付弹窗
      onCreditDialogVisible: false,//选择挂账类型弹窗
      addOnCreditDialogVisible: false,//新增挂账类型弹窗
      addUnitModalVisible: false, // 合约单位弹出框
      hasInitTable0: false, // 区分中西处方
      hasInitTable1: false, // 区分中西处方
      patientFormDisabled: false,//患者表单置灰
      showChargeDtailDialog: false,//查看收费处方详情

      portionRefundDialogVisible: false,//部分零退
      currentRow: null,//选中的明细当前行0 处置项目 1 西药 2 中药 3 检查 4 检验5快速就诊(Bus_id对应医嘱id)
      currentDetailTableData: null,//动态表格数据
      currentFeeType: null,  //记录当前行的 feeType
      dispositionRefundRow: null,  //处置退款选中项
      refundTitel: '',


      //表格数据容器
      patientTabelData: [],//选择患者表格
      tableData1: [],//主表格
      tableData2: [],//西药表格
      tableData3: [],//西药明细
      tableData4: [],//中药明细
      tableData5: [],//处置明细
      tableData6: [],//西药退药数据
      tableData7: [],//退处置数据
      tableData8: [],//中药退药数据
      tableData9: [],//西药关联处置数据
      tableData10: [],//中药关联处置数据
      currentRowData: {},//中西处方选择的当前行数据
      currentRightRowData: {},//中西处方选择的当前行数据


      //下拉框容器
      provinces: [],  // 所有省份
      cityOption: [],     // 当前省下的城市
      countyOption: [],    // 当前市下的区县
      townOption: [],    // 区县下的乡
      villageOption: [],    // 区县下的乡
      prhCostOption: [],//病员费别
      prhTypeOption: [],//病员类别
      rltsEntitiesOption: [],//联系人关系
      contractUnitOption: [],//合约单位
      onCreditOption: [],//挂账类型
      untAtteOption: [],//往来单位新增---单位属性
      deptOptions: [],//科室下拉框
      doctorOptions: [],//医生下拉框
      chargingPriceOptions: [],//项目价格下拉框
      registerOptions: [],//挂号类别
      ntlyOptions: [],//国籍
      medicationFrequencyOptions: [],//给药方式
      medicationWayOptions: [],//用药频率
      dosaUntOptions: [],//单位
      addUnitType: [], //合约单位动态表单
      nationOption: [],//民族下拉框
      certypeOption: [],//证件下拉框
      profttlOption: [],//职业下拉框
      ticketTypeOption: [{id: 1, label: '普通门诊发票'}],
      orderTypeOptions: [{id: 0, label: '西药处方费'}, {id: 1, label: '中药处方费'}, {id: 2, label: '检查费'}, {
        id: 3,
        label: '检验费'
      }, {id: 4, label: '处置项目费'}, {id: 5, label: '快速就诊'}],
      stateOption: [{id: 0, label: '禁用'}, {id: 1, label: '可用'}],
      nuyStateOption: [{id: 0, label: '否'}, {id: 1, label: '冲销原单'}, {id: 2, label: '冲销负单'}],
      opeWayOption: [{id: 0, label: '现场'}, {id: 1, label: '网络'}, {id: 2, label: '自助机'}, {
        id: 3,
        label: '银医通'
      }],
      busFormOption: [{id: 0, label: '医嘱'}, {id: 1, label: '手工'}, {id: 2, label: '护理'}, {id: 3, label: '网络'}],
      feeTypeOption1: [{id: 0, label: '处置项目'}, {id: 1, label: '西药'}, {id: 2, label: '中药'}, {
        id: 3,
        label: '检查'
      }, {id: 4, label: '检验'}, {id: 5, label: '快速就诊'}, {id: 6, label: '关联处置'},],
      timeOption: [{id: 0, label: '选择今天'}, {id: 1, label: '选择昨天'}, {id: 2, label: '选择上月'}, {
        id: 3,
        label: '选择本月'
      }, {id: 4, label: '会计期间'}, {id: 5, label: '选择本年'}, {id: 6, label: '统计上午'}, {
        id: 7,
        label: '统计下午'
      }, {id: 8, label: '统计晚上'},],
      dataSourceOptions: [{id: 1, label: '医嘱'}, {id: 2, label: '护士'}, {id: 3, label: '检查'}, {
        id: 4,
        label: '检验'
      }, {id: 5, label: '其他'}],
      bsSourceOptions: [{id: 4, label: '处置项目'}, {id: 5, label: '挂号收费项目'}],
      chargeStatusOptions: [{id: 0, label: '未收费'}, {id: 1, label: '已收费'}, {id: 2, label: '已申请退费'}, {
        id: 3,
        label: '已退费'
      }],
      executemodeOptions: [{id: 0, label: '否'}, {id: 1, label: '是'}],
      refundOptions: [{id: 1, label: '网络退款'}, {id: 2, label: '现金退款'}],


      // 表格动态列
      tableRows1: [
        {name: "系统序号", prop: "id"},
        {name: "健康序号", prop: "patId"},
        {name: "姓名", prop: "patName"},
        {name: "单据编号", prop: "docNum"},
        {name: "冲销状态", prop: "nuyState", op: 'nuyStateOption'},
        {name: "收费员", prop: "feeUserName"},
        {name: "开单医生", prop: "bilgDrName"},
        {name: "开单科室", prop: "bilgDepName"},
        {name: "应收金额", prop: "receAmt"},
        {name: "实收金额", prop: "paidAmt"},
        {name: "现金支付", prop: "cashAmt"},
        {name: "挂账支付", prop: "bebtAmt"},
        {name: "退款金额", prop: "nuyAmt"},
        /*{name: "减免金额", prop: "derateMoney"},*/
        {name: "支付方式", prop: "opeWay", op: 'opeWayOption'},
        {name: "收费时间", prop: "feeTime"},
        /*{name: "医保支付", prop: "chsAmt"},
        {name: "健康卡支付", prop: "patAmt"},
        {name: "优惠金额", prop: "distAmt"},*/
        {name: "冲销人", prop: "nuyUserName"},
        {name: "冲销时间", prop: "nuyTime"},
        {name: "冲销序号", prop: "nuyId"},
      ],
      tableRows2: [
        {name: "系统序号", prop: "id"},
        {name: "业务来源", prop: "feeType", op: 'feeTypeOption1'},
        {name: "项目名称", prop: "feeTypeName"},
        {name: "数量", prop: "cnt"},
        {name: "实际金额", prop: "paidAmt"},
        {name: "冲销金额", prop: "nuyAmt"},
        {name: "开单科室", prop: "bilgDepName"},
        {name: "开单医生", prop: "bilgDrName"},
        {name: "冲销状态", prop: "nuyState", op: 'nuyStateOption'},
        {name: "冲销序号", prop: "nuyId"},
        {name: "冲销数量", prop: "nuyCnt"},
      ],

      //西医处方
      tableRows3: [
        {name: "药品名称", prop: "drugName"},
        {name: "规格描述", prop: "drugSpec"},
        {name: "单位剂量", prop: "unitDose"},
        {name: "剂量单位", prop: "dosUnt", op: 'dosaUntOptions'},
        {name: "用药剂量", prop: "sdoseSum"},
        {name: "数量", prop: "cnt"},
        {name: "给药方式", prop: "medcWayId", op: 'medicationFrequencyOptions'},
        {name: "用药频率", prop: "usedfrquId", op: 'medicationWayOptions'},
        {name: "成本", prop: "purcAmt"},
        {name: "单价", prop: "salePric"},
        {name: "金额", prop: "saleAmt"},
      ],

      //中药处方
      tableRows4: [
        {name: "药品序号", prop: "drugId"},
        {name: "药品名称", prop: "drugName"},
        {name: "发药数量", prop: "cnt"},
        {name: "单位", prop: "unt", op: 'dosaUntOptions'},
        {name: "成本单价", prop: "purcAmt"},
        {name: "销售金额", prop: "saleAmt"},
        {name: "医保编码", prop: "chsCode"},
        {name: "医保名称", prop: "chsName"},
      ],


      tableRows5: [
        {name: "项目名称", prop: "costname"},
        //{name: "单位", prop: "drugName"},
        //{name: "包数量", prop: "cnt"},
        {name: "数量", prop: "num"},
        {name: "执行金额", prop: "executionAmount"},
        {name: "执行科室", prop: "executDeptId", op: 'deptOptions'},
      ],
      tableRows6: [
        {name: "健康ID", prop: "patId"},
        {name: "健康卡号", prop: "id"},
        {name: "姓名", prop: "name"},
        {name: "身份证号", prop: "certno"},
        {name: "联系电话", prop: "conerTel"},
        {name: "合约单位", prop: "phrUnt", op: 'contractUnitOption'}
      ],
      tableRows7: [
        {name: "系统序号", prop: "id"},
        {name: "药品序号", prop: "drugId"},
        {name: "药品名称", prop: "drugName"},
        {name: "规格描述", prop: "drugSpec"},
        {name: "零售金额", prop: "saleAmt"},
        {name: "数量", prop: "cnt"},
        {name: "包装单位", prop: "pacCnt"},
        {name: "单次剂量", prop: "sdoseCnt"},
        {name: "周期次数", prop: "prdCnt"},
        {name: "周期天数", prop: "prdDays"},
        {name: "总剂量", prop: "sdoseSum"},
      ],

      tableRows9: [
        {name: "系统序号", prop: "id"},
        {name: "药品名称", prop: "drugName"},
        {name: "数量", prop: "cnt"},
        {name: "付数", prop: "tcmCnt"},
        {name: "零售金额", prop: "saleAmt"},
        {name: "给药方式", prop: "medcWayId", op: 'medicationFrequencyOptions'},
        {name: "用药频率", prop: "usedfrquId", op: 'medicationWayOptions'},
        {name: "总剂量", prop: "sdoseSum"},
        {name: "剂量单位", prop: "sdoseUnt", op: 'dosaUntOptions'},
      ],
      tableRows8: [
        {name: "系统序号", prop: "id"},
        {name: "处置名称", prop: "costname"},
        {name: "处置类型", prop: "dataSource", op: 'dataSourceOptions'},
        {name: "收费状态", prop: "chargeStatus", op: 'chargeStatusOptions'},
        {name: "频率数量", prop: "frquCnt"},
        {name: "执行单价", prop: "executionPrice"},
        {name: "执行金额", prop: "executionAmount"},
        {name: "执行频率", prop: "exeFrquId", op: 'medicationWayOptions'},
        {name: "数量", prop: "num"},
        {name: "申请退数量", prop: "applyNum"},
      ],

      tableRows10: [
        {name: "系统序号", prop: "id"},
        {name: "处置类型", prop: "feeTypeName"},
        {name: "数量", prop: "cnt"},
        {name: "标准单价", prop: "stanPric"},
        {name: "实际金额", prop: "paidAmt"},
        {name: "业务来源", prop: "busForm",op:'busFormOption'},
        {name: "执行科室", prop: "bilgDepName"},
        {name: "执行医生", prop: "bilgDrName"},
      ],

      //表单
      addUnitForm: {
        id: null,
        code: '',
        state: 1,
        area: 1,
        name: '',
        pyCode: '',
        bankName: '',
        bankNo: '',
        splerPmtno: '',
        legalRepe: '',
        mainConer: '',
        conerPhone: '',
        conerTel: '',
        conerQq: '',
        conerFax: '',
        conerPostc: '',
        url: '',
        conerMail: '',
        untAtte: 3,
        uscc: '',
        conerAdd: '',
        remark: ''
      },//合约单位新增修改表单
      addOnCreditForm: {
        beginTime: '',
        code: '',
        cotUnit: null,
        endTime: '',
        name: '',
        pycode: '',
        remarks: '',
        state: 1,
      },//挂账类型新增修改表单
      patientChooseForm: {
        id: null,
        patId: '',
        name: '',
        sex: null,
        certno: null,
        conerTel: null,
        contractUnit: null,
        healthCardNo: null,
        cardType: null,
      },//选择患者表单
      queryConditionForm: {
        id: null,
        patId: '',
        chargePerson: null,
        patientType: null,
        opeWay: null,
        timeFrameArr: [
          dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
          dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')
        ],
        timeFrame: 0,
        docNum: '',
      },//表格头表单
      paymentForm: {
        age: null,
        aliAmt: null,
        bankAmt: null,
        bebtAmt: null,
        bebtId: null,
        bebtType: '',
        bilgDepId: null,
        bilgDepName: '',
        bilgDrId: null,
        bilgDrName: '',
        cashAmt: null,
        chsAmt: null,
        distAmt: null,
        groupAmt: null,
        invoNo: '',
        opeWay: null,
        paidAmt: null,
        patAmt: null,
        patCostType: null,
        patId: null,
        patName: '',
        patType: null,
        recdAmt: null,
        receAmt: null,
        regId: null,
        remarks: '',
        seeId: null,
        sex: null,
        shHarId: null,
        wechatAmt: null,
        balance: null,
        observation: null,
        observationAdvance: null,
        change: null,
      },//门诊收费结算表单
      patientForm: {
        id: null,
        patId: '',       // 健康ID
        thrNot: false,   // 三无（复选框应为布尔值）
        name: '',           // 姓名
        sex: null,       // 性别
        identityCard: 1,
        certno: '',   //证件号码
        brdy: '',      // 出生日期
        ageYear: null,        // 年龄-岁
        ageMonth: null,       // 年龄-月
        naty: '汉族',     // 民族
        jobId: null,            // 职业
        feeType: null, // 病员费别
        prhType: null, // 病员类型
        contractUnit: null,  // 合约单位
        isSpecial: '否',    // 特殊人群
        conerName: '',        // 联系人
        conerTel: '',          // 联系电话
        conerRltsId: null, // 联系人关系
        province: '',       // 省
        city: '',           // 市
        county: '',         // 县
        town: '',           // 乡
        village: '',         //村
        registerDate: new Date().toISOString().split('T')[0],   // 挂号日期
        timeSlot: '1',       // 时段
        department: null,     // 科室
        doctor: null,         // 医生
        registerType: null,   // 挂号类别
        clinicRoom: null,  // 诊室
        existNumber: null,
        currentNumber: null,
        caseHistory: null,
        total: null,
        naplAddCode: null,
        conerAddCode: null,
        number: null,
      },//患者信息表单
      refundForm: {
        id:null,
        detailId: null,
        bebtAmt: null,
        cashAmt: null,
        groupAmt: null,
      },

      finalReportForm: {

      },
      westRefundRelevance : [],
      chinaRefundRelevance : [],
      refundFormRules: {
        cnt: [
          {required: true, message: '退费数量不能为空', trigger: 'blur'},      // 必填
          {type: 'number', message: '必须为数字', trigger: 'blur'},            // 必须为数字
          {validator: this.validateNuyCnt, trigger: 'blur'}                   // 自定义验证（最小值）
        ]
      },

      //新增健康档案表单
      celerityFilingForm: {
        name: '',           // 姓名
        sex: null,       // 性别
        identityCard: 1,
        certno: '',   //证件号码
        brdy: '',      // 出生日期
        ageYear: 0,        // 年龄-岁
        ageMonth: 0,       // 年龄-月
        ageDay: 0,       // 年龄-天
        naty: 1,     // 民族
        ntlyId: 1,    //国籍
        jobId: '',            // 职业
        prhType: null, // 病员类型
        contractUnit: null,  // 合约单位
        conerName: '',        // 联系人
        conerTel: '',          // 联系电话
        conerRltsId: null, // 联系人关系
        province: '',       // 省
        city: '',           // 市
        county: '',         // 县
        town: '',           // 乡
        village: '',         //村
        tel: null,
        restAddCode: null,
        naplAddCode: null,
      },


      //表单验证
      addOnCreditFormRules: {
        code: [
          {required: true, message: '请输入编码', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur'}
        ],
        cotUnit: [
          {required: true, message: '请选择合约单位', trigger: 'change'}
        ],
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur'}
        ],

        beginTime: [
          {required: true, message: '请选择开始时间', trigger: 'change'}
        ],
        endTime: [
          {required: true, message: '请选择结束时间', trigger: 'change'},
          {
            validator: (rule, value, callback) => {
              if (this.addOnCreditForm.beginTime && value) {
                if (new Date(value) < new Date(this.addOnCreditForm.beginTime)) {
                  callback(new Error('结束时间不能早于开始时间'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      }, //挂账
      addUnitRules: {
        code: [{required: true, message: '请填写合约单位编码！', trigger: 'change'}],
        name: [{required: true, message: '请填写合约单位名称！', trigger: 'change'}],
      },//合约单位

    };
  },
  computed: {
    // 当前表格列配置
    currentTableRows() {
      switch (this.currentFeeType) {
        case 0:
          return this.tableRows5;
        case 1:
          return this.tableRows3;
        case 2:
          return this.tableRows4;
        default:
          return this.tableRows3; // 默认
      }
    },

    // 当前表格数据
    currentTableData() {
      switch (this.currentFeeType) {
        case 0:
          return this.tableData5;
        case 1:
          return this.tableData3;
        case 2:
          return this.tableData4;
      }
    },

    // 当前汇总方法
    currentSummaryMethod() {
      switch (this.currentFeeType) {
        case 0:
          return this.getSummaries5;
        case 1:
          return this.getSummaries3;
          //case 2: return this.getSummaries4;
        default:
          return this.getSummaries3;
      }
    },
  },
  beforeDestroy() {
    // 组件销毁时移除监听，避免内存泄漏
    window.removeEventListener('keydown', this.handleKeyPress);
  },
  watch: {
    tableData1: {
      handler(newVal) {
        if (newVal.length < 1) {
          this.tableData2 = []; // 西药表格
          this.tableData3 = []; // 西药明细
          this.tableData4 = []; // 中药明细
          this.tableData5 = []; // 处置明细
          this.tableData6 = []; // 西药退药数据
          this.tableData7 = []; // 退处置数据
          this.tableData8 = []; // 中药退药数据
        }
      },
      deep: true // 如果需要深度监听数组内容变化
    }
  },
  mounted() {
    this.addUnitType = AddType.map(function (v) {
      return v
    })
    window.addEventListener('keydown', this.handleKeyPress);
    this.loadData();
    this.getArea();
    this.getDoctorList();
    this.getDeptList();
    this.getMedicationWay();
    this.dict();
    this.getChargingPrice();
    this.$nextTick(() => {
      this.updateWindowWidth();
      window.addEventListener('resize', this.updateWindowWidth);
    })
  },

  methods: {
    handleOpenFinalReport(){
      this.finalReportDialogVisible = true;
    },
    handleChinaRefundRelevance(selected){
      this.chinaRefundRelevance = JSON.parse(JSON.stringify(selected))
    },
    handleWestRefundRelevance(selected){
      this.westRefundRelevance = JSON.parse(JSON.stringify(selected))
    },
    async handleDispositionConfirmRefund(row) {
      this.refundForm.paidAmt = row.executionPrice * row.applyNum;
      this.refundForm.cnt = row.applyNum;
      this.refundForm.detailId = this.currentDetailTableData.id;
      this.refundForm.type = this.currentRowData.opeWay === 1 ? 1 : 2;
      this.portionRefundDialogVisible = true;
    },
    async handleDispositionRefund(row) {
      await withLoading(this, '退款处理中...')(async () => {
        const res = await refundDoctordispose({id: row.id});
        if (res.code === 200) {
          const res = await getDoctordisposeOneById(this.currentDetailTableData.busId);
          if (res.code !== 200) return this.$message.warning(res.message)
          res.data.costname = this.currentDetailTableData.costNane;
          this.tableData7 = [];
          this.tableData7.push(res.data);
        } else {
          this.$message.error(res.message)
        }
      });
    },
    async handleWestRefund() {
      /*this.currentRowData  退款方式
      this.westRefundRelevance 退款多选组*/
      await withLoading(this, '退款处理中...')(async () => {

        const refundListVOList = [
          ...this.westRefundRelevance.map(item => ({
            detailId: item.id,
            nuyAmt: item.paidAmt,
          })),
          ...this.tableData6.map(item => ({
            detailId: this.currentDetailTableData.id,
            nuyAmt: Math.abs(Number(item.saleAmt)),
          })),
        ];
        const total1 = this.westRefundRelevance?.reduce((sum, item) => sum + (Number(item.paidAmt) || 0), 0);
        const total2 = this.tableData6.reduce((sum, item) => sum + (Math.abs(Number(item.saleAmt)) || 0), 0);
        if (this.currentRowData.groupAmt > 0){
          this.refundForm = Object.assign({}, this.$options.data.call(this).refundForm)
          this.refundForm.cashAmt = 0;
          this.refundForm.bebtAmt = 0;
          this.refundForm.groupAmt = 0;
          this.refundForm.id = this.currentDetailTableData.id;
        }else{
          this.refundForm.cashAmt = this.currentRowData.bebtAmt > 0 ? (total1+total2) - Number(this.currentRowData.bebtAmt) : (total1+total2);
          this.refundForm.bebtAmt = this.currentRowData.bebtAmt;
          this.refundForm.groupAmt = 0;
          this.refundForm.id = this.currentRowData.id;
        }
        this.refundForm.refundListVOList = refundListVOList;
        this.refundTitel = '全部退款';
        this.portionRefundDialogVisible = true;

        /*const newItem = {
          id:this.currentRowData.id,
          refundListVOList
        }
        console.log(newItem,'newItemnewItemnewItemnewItem')
        const res = await westRefundRelevance(newItem);
        if (res.code === 200) {
          await this.loadData();
          this.westReturnMoneyDialogVisible = false;
        } else {
          this.$message.error(res.message)
        }*/
      });
    },

    async handleChinaRefund() {
      await withLoading(this, '退款处理中...')(async () => {
        const refundListVOList = [
          ...this.chinaRefundRelevance.map(item => ({
            detailId: item.id,
            nuyAmt: item.paidAmt,
          })),
          {
            detailId: this.currentDetailTableData.id,
            nuyAmt: this.currentDetailTableData.paidAmt,
          }
        ];
        const total1 = this.chinaRefundRelevance?.reduce((sum, item) => sum + (Number(item.paidAmt) || 0), 0);
        const total2 = this.tableData8.reduce((sum, item) => sum + (Math.abs(Number(item.saleAmt)) || 0), 0);
        if (this.currentRowData.groupAmt > 0){
          this.refundForm = Object.assign({}, this.$options.data.call(this).refundForm)
          this.refundForm.cashAmt = 0;
          this.refundForm.bebtAmt = 0;
          this.refundForm.groupAmt = 0;
          this.refundForm.id = this.currentDetailTableData.id;
        }else{
          this.refundForm.cashAmt = this.currentRowData.bebtAmt > 0 ? (total1+total2) - Number(this.currentRowData.bebtAmt) : (total1+total2);
          this.refundForm.bebtAmt = this.currentRowData.bebtAmt;
          this.refundForm.groupAmt = 0;
          this.refundForm.id = this.currentRowData.id;
        }
        this.refundForm.refundListVOList = refundListVOList;
        this.refundTitel = '全部退款';
        this.portionRefundDialogVisible = true;
      });
    },
    handleKeyPress(event) {
      // 检查是否为 F9 键（兼容 key 和 keyCode）
      if (event.key === 'F9' || event.keyCode === 120) {
        event.preventDefault(); // 阻止默认行为
        this.handleIdCardData(); // 调用你的业务方法
      }
    },
    async handleIdCardData() {
      await withLoading(this, '读取身份证中...')(async () => {
        try {
          const res = await readIdCard();
          this.queryConditionForm.patId = res.cardno;
          await this.handleSearch();
        } catch (error) {
          this.$message.error(error)
        }
      });
    },

    planChargeListRegistrationSlip() {

      return {
        ...this.currentRowData,
        cashAmt: this.currentRowData.cashAmt + '(元)',
        receAmt: this.currentRowData.receAmt + '(元)',
        name: this.currentRowData.patName,
        sex: this.currentRowData.sex === 1 ? '男' : '女',
        age: this.currentRowData.age + '岁',
        patId: this.currentRowData.patCode,
        oneDimensionalCode: this.generateBarcodeBase64(this.currentRowData.patId),
        disposeCost: this.currentRightRowData
            .filter(item => [0, 6].includes(item.feeType))
            .reduce((sum, item) => sum + (item.paidPric || 0), 0) + '(元)',
        westCost: this.currentRightRowData
            .filter(item => item.feeType === 1).reduce((sum, item) => sum + (item.paidPric || 0), 0) + '(元)',
        registrationCost: this.currentRightRowData
            .filter(item => item.feeType === 5).reduce((sum, item) => sum + (item.paidPric || 0), 0) + '(元)',
        printTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        chargeUser: this.currentRowData.feeUserName,
      }
    },
    generateBarcodeBase64(text) {
      const canvas = document.createElement('canvas');
      JsBarcode(canvas, text, {
        format: 'CODE128',
        width: 1,
        displayValue: false,
      });
      return canvas.toDataURL('image/png');
    },
    printChargeList() {
      if (!this.currentRowData.patName?.trim()) {
        this.$message.warning("请选中需要打印数据")
        return;
      }
      printUtil.init(chargeListRegistrationSlip);
      printUtil.print(this.planChargeListRegistrationSlip());
    },
    computeRefundAmt() {
      //this.refundForm.paidAmt = this.currentDetailTableData.
    },

    validateNuyCnt(rule, value, callback) {
      if (value === null || value === '') {
        callback(new Error('退费数量不能为空'));
        return;
      }
      if (isNaN(value)) {
        callback(new Error('必须为有效数字'));
        return;
      }
      if (value < 1) {
        callback(new Error('退费数量必须 ≥1'));
        return;
      }
      if (this.currentDetailTableData?.cnt !== undefined && value > this.currentDetailTableData.cnt) {
        callback(new Error(`退费数量不能超过明细数量${this.currentDetailTableData.cnt}`));
        return;
      }
      // 验证通过
      callback();
    },

    async handlePortionRefund() {
      if (this.currentDetailTableData === null) {
        this.$message.warning("请选择要零退的明细数据")
        return;
      }
      this.refundTitel = '部分零退';
      await this.getDosaUnt();
      if (this.currentDetailTableData.feeType === 0) {
        const res = await getDoctordisposeOneById(this.currentDetailTableData.busId);
        if (res.code !== 200) return this.$message.warning(res.message)
        res.data.costname = this.currentDetailTableData.costNane;
        this.tableData7 = [];
        this.tableData7.push(res.data);
        this.dispositionReturnMoneyDialogVisible = true;
        return;
      }

      if (this.currentDetailTableData.feeType === 1) {
        const res = await getDrxMainRefundList({id: this.currentDetailTableData.id});
        console.log(res,'resresresresresresres')
        console.log(res,'resresresresresresres')
        if (res.code !== 200) return this.$message.warning(res.message)
        this.tableData6 = res.data.dugDrxDetailsList;
        if (res.data?.cncDFeeListdetailsResp?.length > 0) {
          this.tableData9 = res.data.cncDFeeListdetailsResp;
        }
        this.westReturnMoneyDialogVisible = true;
        return;
      }

      if (this.currentDetailTableData.feeType === 2) {
        const res = await getDtcmRxMainRefundList({id: this.currentDetailTableData.id});
        if (res.code === 200) {
          this.tableData8 = res.data.dugDrxTcmDetailsList;
          this.tableData10 = res.data.cncDFeeListdetailsResp;
          this.chinaReturnMoneyDialogVisible = true;
        } else {
          this.$message.error(res.message)
        }
        return;
      }

      if (!this.westReturnMoneyDialogVisible && !this.chinaReturnMoneyDialogVisible){
        this.refundForm.cashAmt = this.currentDetailTableData.paidAmt;
        this.refundForm.groupAmt = 0;
        this.refundForm.detailId = this.currentDetailTableData.id;
        this.refundForm.bebtAmt = 0;
        this.portionRefundDialogVisible = true;
        return ;
      }
      this.refundForm.cashAmt = this.currentRowData.cashAmt;
      this.refundForm.groupAmt = this.currentRowData.groupAmt;
      this.refundForm.detailId = this.currentDetailTableData.id;
      this.refundForm.bebtAmt = this.currentRowData.bebtAmt;
      this.portionRefundDialogVisible = true;
    },

    handleCloseRefund() {
      this.refundForm = Object.assign({}, this.$options.data.call(this).refundForm);
      this.portionRefundDialogVisible = false;
    },

    handleCloseFinalReport() {
      this.finalReportForm = Object.assign({}, this.$options.data.call(this).finalReportForm);
      this.finalReportDialogVisible = false;
    },

    async handleConfirmRefund() {

      const valid = this.$refs.refundForm.validate();
      if (!valid) return;
      if (this.refundTitel === '全部退款'){
        console.log(this.refundForm,'this.refundFormthis.refundFormthis.refundForm')
          const res = await westRefundRelevance(this.refundForm);
          if (res.code === 200){
            await this.handleConditionQuery();
            await new Promise(resolve => setTimeout(resolve, 500));
            await this.handleCurrentRow(this.currentRowData);
            this.portionRefundDialogVisible = false;
            this.westReturnMoneyDialogVisible = false;
          } else {
            this.$message.warning(res.message);
          }
      } else {
        const refundVO = {
          detailId: Number(this.refundForm.detailId), // 确保是数字类型
          bebtAmt: this.refundForm.bebtAmt, // 注意参数名修正
          cashAmt: this.refundForm.cashAmt,
          groupAmt: this.refundForm.groupAmt,
        }
        await withLoading(this, '零退处理中...')(async () => {
          const res = await portionRefundByDetail(refundVO);
          if (res.code === 200) {
            this.dispositionReturnMoneyDialogVisible = false;
            this.portionRefundDialogVisible = false;
            await this.handleConditionQuery();
            await new Promise(resolve => setTimeout(resolve, 500));
            await this.handleCurrentRow(this.currentRowData);
          } else {
            this.$message.error(res.message || '零退费操作失败，请联系管理员！');
          }
        });
      }
    },

    async handleFullRefund() {
      if (!this.currentRowData || Object.keys(this.currentRowData).length === 0) {
        return this.$message.warning("请选择退费患者后进行操作！");
      }

      if (this.currentRowData.nuyState !== 0) {
        return this.$message.warning(`订单${this.currentRowData.docNum}已冲销!`);
      }
      try {
        // 添加确认弹框
        const confirmResult = await this.$confirm(
            `确定要执行患者【${this.currentRowData.patName}】的整单退费吗?`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        ).catch(() => {
          this.$message.warning('已取消退费操作');
          return false;
        });
        if (!confirmResult) return;
        const res = await fullRefund({
          id: this.currentRowData.id,
          type: this.currentRowData.opeWay === 1 ? 1 : 2
        });
        if (res.code === 200) {
          this.handleLeftTableRowClick(this.currentRowData);
          await this.handleConditionQuery();
        } else {
          this.$message.error('整单退费失败，请联系管理员！');
        }
      } catch (error) {
        this.$message.error('系统异常，请联系管理员');
      }
    },
    currentDetailRefund(row) {
      this.currentDetailTableData = JSON.parse(JSON.stringify(row));
      console.log(this.currentDetailTableData, 'this.currentDetailTableDatathis.currentDetailTableData')
    },
    handleFastRefund() {

    },

    getNuyStateTagType(nuyState) {
      switch (nuyState) {
        case 0:
          return 'success'      // 否 - 灰色
        case 1:
          return 'warning'   // 冲销原单 - 橙色
        case 2:
          return 'danger'    // 冲销负单 - 红色
        default:
          return ''
      }
    },

    // 获取冲销状态的显示文本
    getNuyStateLabel(nuyState) {
      const option = this.nuyStateOption.find(item => item.id === nuyState)
      return option ? option.label : ''
    },

    handleClosePds() {
      this.tableData3 = [];
      this.tableData4 = [];
      this.tableData5 = [];
      this.showChargeDtailDialog = false;
    },
    handleLeftTableRowClick(row) {
      this.tableData3 = [];
      this.tableData4 = [];
      this.tableData5 = [];
      this.currentFeeType = row.feeType;
      this.showPrescriptionDetails = true;
      this.loadRightTableData(row);
    },

    async loadRightTableData(row) {
      try {
        let apiResponse;

        this.$nextTick(() => {
          this.$refs.rightTable?.doLayout(); // 强制重新渲染表格
        });
        switch (row.feeType) {
          case 0:
            apiResponse = await getDoctordispose({seeDoctorId: row.seeId});
            if (apiResponse.code !== 200) throw apiResponse;
            this.tableData5 = apiResponse.data;
            break;

          case 1:
            apiResponse = await getWestPrescription(row.busId);
            console.log(row, 'apiResponseapiResponseapiResponse')
            console.log(apiResponse, 'apiResponseapiResponseapiResponse')
            if (apiResponse.code !== 200) throw apiResponse;
            this.tableData3 = apiResponse.data.drxDetails;
            await Promise.all([
              this.getMedicationWay(),
              this.getMedicationFrequency(),
              this.getDosaUnt()
            ]);
            break;

          case 2:
            apiResponse = await getChinaPrescription({id: row.busId});
            if (apiResponse.code !== 200) throw apiResponse;
            this.tableData4 = apiResponse.data.tcmDetailsRespVOS;
            break;
        }

      } catch (error) {
        console.error('数据加载失败:', error);
        this.$message.error(error.message || '系统异常，请稍后重试');
        this.tableData3 = [];
        this.tableData4 = [];
        this.tableData5 = [];
      }
    },

    async handleDbShowChargeDetail(row) {
      /*if (row.nuyState === 1 || row.nuyState === 2) return;*/
      try {
        if (!row.patName?.trim()) {
          this.$message.warning("请选中需要查看的行数据");
          return
        }
        await this.handleCurrentRow(row);
        this.showChargeDtailDialog = true;
        this.$refs.rightTable.$forceUpdate();
        [0, 1, 2].includes(this.tableData2[0].feeType) ? this.showPrescriptionDetails = true : this.showPrescriptionDetails = false;
        if ([0, 1, 2].includes(this.tableData2[0].feeType)) {
          await this.getMedicationWay();
          await this.getMedicationFrequency();
          await this.getDosaUnt();
          this.currentFeeType = this.tableData2[0].feeType;
          await this.loadRightTableData(this.tableData2[0]);
          this.tableKey++;
        }
      } catch (error) {
        console.log(error, 'errorerrorerror')
        this.$message.error("系统异常:请联系管理员!!!")
      } finally {

      }

    },

    async handleConditionQuery() {
      const [start, end] = this.queryConditionForm.timeFrameArr || [];

      // 校验结束时间不能早于开始时间
      if (start && end && dayjs(end).isBefore(dayjs(start))) {
        this.$message.error('结束时间不能早于开始时间！');
        return;
      }
      await this.loadData();
    },

    handleTimeChange(selectedId) {
      switch (selectedId) {
        case 0: // 今天
          this.queryConditionForm.timeFrameArr = [
            dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss').toString(),
            dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss').toString()
          ];
          this.handleConditionQuery();
          break;

        case 1: // 昨天
          this.queryConditionForm.timeFrameArr = [
            dayjs().subtract(1, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss'),
            dayjs().subtract(1, 'day').endOf('day').format('YYYY-MM-DD HH:mm:ss')
          ];
          this.handleConditionQuery();
          break;

        case 2: // 上月
          this.queryConditionForm.timeFrameArr = [
            dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD HH:mm:ss'),
            dayjs().subtract(1, 'month').endOf('month').format('YYYY-MM-DD HH:mm:ss')
          ];
          this.handleConditionQuery();
          break;

        case 3: // 本月
          this.queryConditionForm.timeFrameArr = [
            dayjs().startOf('month').format('YYYY-MM-DD HH:mm:ss'),
            dayjs().endOf('month').format('YYYY-MM-DD HH:mm:ss')
          ];
          this.handleConditionQuery();
          break;

        case 4: // 会计期间（需自定义）
          this.queryConditionForm.timeFrameArr = [
            dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
            dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')
          ];
          this.handleConditionQuery();
          break;

        case 5: // 本年
          this.queryConditionForm.timeFrameArr = [
            dayjs().startOf('year').format('YYYY-MM-DD HH:mm:ss'),
            dayjs().endOf('year').format('YYYY-MM-DD HH:mm:ss')
          ];
          this.handleConditionQuery();
          break;

        case 6: // 上午（8:00 - 12:00）
          this.queryConditionForm.timeFrameArr = [
            dayjs().set('hour', 8).set('minute', 0).set('second', 0).format('YYYY-MM-DD HH:mm:ss'),
            dayjs().set('hour', 12).set('minute', 0).set('second', 0).format('YYYY-MM-DD HH:mm:ss')
          ];
          this.handleConditionQuery();
          break;

        case 7: // 下午（13:00 - 17:00）
          this.queryConditionForm.timeFrameArr = [
            dayjs().set('hour', 13).set('minute', 0).set('second', 0).format('YYYY-MM-DD HH:mm:ss'),
            dayjs().set('hour', 17).set('minute', 0).set('second', 0).format('YYYY-MM-DD HH:mm:ss')
          ];
          this.handleConditionQuery();
          break;

        case 8: // 晚上（18:00 - 22:00）
          this.queryConditionForm.timeFrameArr = [
            dayjs().set('hour', 18).set('minute', 0).set('second', 0).format('YYYY-MM-DD HH:mm:ss'),
            dayjs().set('hour', 22).set('minute', 0).set('second', 0).format('YYYY-MM-DD HH:mm:ss')
          ];
          this.handleConditionQuery();
          break;

        default: // 默认今天
          this.queryConditionForm.timeFrameArr = [
            dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss').toString(),
            dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss').toString()
          ];
          this.handleConditionQuery();
      }
    },

    async loadData() {
      const res = await getChargeList({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        condition: this.queryConditionForm.patId === '' ? '' : this.queryConditionForm.patId,
        startTime: this.queryConditionForm.timeFrameArr[0],
        endTime: this.queryConditionForm.timeFrameArr[1],
        patType: this.queryConditionForm.patientType ?? null,
        opeWay: this.queryConditionForm.opeWay ?? null,
        docNum: this.queryConditionForm.docNum === '' ? '' : this.queryConditionForm.docNum,
      });
      if (res.code === 200) {
        this.tableData1 = res.data.content
            .map(item => ({
              ...item,
              feeTime: item.feeTime === null ? null : dayjs(item.feeTime).format('YYYY-MM-DD HH:mm:ss'),
              crateTime: item.crateTime === null ? null : dayjs(item.crateTime).format('YYYY-MM-DD HH:mm:ss'),
              nuyTime: item.nuyTime === null ? null : dayjs(item.nuyTime).format('YYYY-MM-DD HH:mm:ss'),
            }))
        this.totalSize = res.data.totalSize;
      }

    },


    //挂账类型修改模态框回显
    async handleOpenEditOnCredit(item) {
      const res = await getOnCreditById({id: item.id});

      const formatTime = (timestamp) => {
        if (!timestamp) return '';
        const date = new Date(timestamp.toString().length === 10 ? timestamp * 1000 : timestamp);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
      };

      this.addOnCreditForm = {
        ...res.data,
        beginTime: formatTime(res.data.beginTime),
        endTime: formatTime(res.data.endTime)
      };
      await this.getContuntList();
      this.addOnCreditDialogVisible = true;
    },

    //挂账类型新增模态框处理
    handleOpenAddOnCredit() {
      this.getContuntList();
      this.addOnCreditDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.addOnCreditForm.clearValidate();
      });
    },

    //清空挂账类型数据
    handleCloseAddOnCredit() {
      this.addOnCreditForm = {};
      this.addOnCreditForm.state = 1;
      this.addOnCreditDialogVisible = false;
    },

    //挂账类型名称转拼音
    handleOnCreditNameGetPy() {
      this.addOnCreditForm.pycode =
          pinyin(this.addOnCreditForm.name, {pattern: 'first', toneType: 'none', separator: ''}).toLocaleUpperCase();
    },

    //新增修改挂账类型
    async handleAddOnCredit() {
      try {
        // 验证表单
        const valid = await this.$refs.addOnCreditForm.validate();
        if (!valid) {
          this.$message.warning('请完善表单信息');
          return false;
        }

        let res;
        // 判断是新增还是编辑
        if (this.addOnCreditForm.id) {
          // 有id -> 编辑操作
          res = await editOnCredit(this.addOnCreditForm);
        } else {
          // 无id -> 新增操作
          res = await addOnCredit(this.addOnCreditForm);
        }

        // 统一处理响应
        if (res.code === 200) {
          this.addOnCreditDialogVisible = false;
          this.handleCloseAddOnCredit();
          await this.getOnCreditList();
          this.onCreditDialogVisible = true;
        } else {
          this.$message.error(res.message || '操作失败');
        }
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('操作失败，请重试');
      }
    },

    //挂账类型下拉框
    async getOnCreditList() {
      const res = await getOnCreditList()
      this.onCreditOption = res.data.map(item => {
        return {
          id: item.id, label: item.name
        }
      })
    },

    //门诊收费确认结算
    async handleConfirmPayment() {
      if (this.paymentForm.bebtAmt != null) {
        await this.getOnCreditList();
        this.onCreditDialogVisible = true;
      }
    },

    //确认选择挂账类型
    handleConfirmPayment2() {
      this.paymentForm.bilgDrId = 31;
      this.paymentForm.opeWay = 0;
      this.paymentForm.patId = this.patientForm.patId;
      this.paymentForm.patName = this.patientForm.name;
      this.paymentForm.regId = this.patientForm.name;
    },

    //结算模态框 计算各种金额
    calculatePayments() {
      // ========== 新增：正则过滤所有金额字段 ==========
      const validateAmount = (value) => {
        const num = Number(value);
        // 允许空值或非负数
        return value === '' || (!isNaN(num) && num >= 0);
      };

      // 校验所有支付金额字段
      const amountFields = [
        this.outpatientChargesForm.currentTotal, // 应收金额
        this.paymentForm.chsAmt,    // 医保
        this.paymentForm.bankAmt,   // 银联
        this.paymentForm.bebtAmt,   // 挂账
        this.paymentForm.groupAmt,  // 网络
        this.paymentForm.patAmt     // 健康卡
      ];

      if (!amountFields.every(validateAmount)) {
        this.$message.warning('请输入有效的正数金额');
        return; // 如果校验失败，终止计算
      }

      // ========== 原计算逻辑 ==========
      // 1. 获取应收金额（已通过校验，可直接转换）
      const total = Number(this.outpatientChargesForm.currentTotal) || 0;

      // 2. 计算非现金支付总额（已通过校验，可直接转换）
      const nonCashPaid = [
        this.paymentForm.chsAmt,
        this.paymentForm.bankAmt,
        this.paymentForm.bebtAmt,
        this.paymentForm.groupAmt,
        this.paymentForm.patAmt
      ].reduce((sum, val) => sum + (Number(val) || 0), 0);

      // 3. 计算现金支付缺口
      const cashGap = total - nonCashPaid;

      // 4. 同步现金支付和收到金额
      this.paymentForm.cashAmt = cashGap.toFixed(2);
      this.paymentForm.recdAmt = Math.max(0, cashGap).toFixed(2);

      // 5. 应退找零处理
      this.paymentForm.change = cashGap < 0 ? cashGap.toFixed(2) : "0.00";
    },

    //打开结算模态框
    handleSettleAccounts() {
      this.settleAccountsDialogVisible = true;

      this.paymentForm.cashAmt = this.outpatientChargesForm.currentTotal;
      this.$nextTick(() => {
        // 找到 ref="recdAmt" 的输入框并聚焦
        if (this.$refs.recdAmt) {
          this.$refs.recdAmt.focus();
        }
      });
    },

    //单位剂量 最小剂量下拉框
    async getDosaUnt() {
      const res = await getDosaUnt();
      this.dosaUntOptions = res.data.map(item => {
        return {
          id: item.id, label: item.name
        }
      })
    },

    //给药方式下拉框
    async getMedicationFrequency() {
      if (this.medicationFrequencyOptions.length > 0) return;
      const res = await getMedicationFrequency();
      this.medicationFrequencyOptions = res.data.map(item => {
        return {
          id: item.id, label: item.name
        }
      })
    },

    //用药频率下拉框
    async getMedicationWay() {
      if (this.medicationWayOptions.length > 0) return;
      const res = await getMedicationWay();
      this.medicationWayOptions = res.data.map(item => {
        return {
          id: item.id, label: item.name, frquCnt: item.frquCnt
        }
      })
    },

    //表格合计列计算
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];

      // 需要计算的字段配置
      const calcFields = {
        'receAmt': '应收金额',
        'paidAmt': '实收金额',
        'cashAmt': '现金支付',
        'chsAmt': '医保支付',
        'patAmt': '健康卡支付',
        'distAmt': '优惠金额',
        'bebtAmt': '挂账支付',
      };

      columns.forEach((column, index) => {
        // 第一列显示行号（留空）
        if (index === 0) {
          sums[index] = '';
          return;
        }

        // 第二列（剂量单位）显示"合计"文字
        if (index === 1) {
          sums[index] = '合计';
          return;
        }

        // 只处理需要计算的字段
        if (calcFields[column.property]) {
          const total = data.reduce((sum, item) => {
            const value = parseFloat(item[column.property]) || 0;
            return sum + value;
          }, 0);

          // 如果是cnt列，显示为整数，否则保留两位小数
          sums[index] = column.property === 'cnt'
              ? Math.round(total).toString()
              : total.toFixed(2);
        } else {
          // 其他列显示占位符（与图片中的"一"一致）
          sums[index] = '';
        }
      });

      return sums;
    },

    getSummaries2(param) {
      const {columns, data} = param;
      const sums = [];

      // 需要计算的字段配置
      const calcFields = {
        'detailsCnt': '明细数量',
        'cnt': '数量',
        'nuyCnt': '冲销数量',
        'nuyAmt': '冲销金额',
        'patAmt': '健康卡支付',
        'paidAmt': '实际金额',
      };

      columns.forEach((column, index) => {
        // 第一列显示行号（留空）
        if (index === 0) {
          sums[index] = '';
          return;
        }

        // 第二列（剂量单位）显示"合计"文字
        if (index === 1) {
          sums[index] = '合计';
          return;
        }

        // 只处理需要计算的字段
        if (calcFields[column.property]) {
          const total = data.reduce((sum, item) => {
            const value = parseFloat(item[column.property]) || 0;
            return sum + value;
          }, 0);

          // 如果是cnt列，显示为整数，否则保留两位小数
          sums[index] = column.property === 'cnt'
              ? Math.round(total).toString()
              : total.toFixed(2);
        } else {
          // 其他列显示占位符（与图片中的"一"一致）
          sums[index] = '';
        }
      });

      return sums;
    },

    getSummaries3(param) {
      const {columns, data} = param;
      const sums = [];

      // 需要计算的字段配置
      const calcFields = {
        'cnt': '数量',
        'purcPric': '成本单价',
        'salePric': '单价',
        'saleAmt': '金额',
      };

      columns.forEach((column, index) => {
        // 第一列显示行号（留空）
        if (index === 0) {
          sums[index] = '';
          return;
        }

        // 第二列（剂量单位）显示"合计"文字
        if (index === 1) {
          sums[index] = '合计';
          return;
        }

        // 只处理需要计算的字段
        if (calcFields[column.property]) {
          const total = data.reduce((sum, item) => {
            const value = parseFloat(item[column.property]) || 0;
            return sum + value;
          }, 0);

          // 如果是cnt列，显示为整数，否则保留两位小数
          sums[index] = column.property === 'cnt'
              ? Math.round(total).toString()
              : total.toFixed(2);
        } else {
          // 其他列显示占位符（与图片中的"一"一致）
          sums[index] = '';
        }
      });

      return sums;
    },

    getSummaries5(param) {
      const {columns, data} = param;
      const sums = [];

      // 需要计算的字段配置
      const calcFields = {
        'num': '数量',
        'executionAmount': '执行金额',
      };

      columns.forEach((column, index) => {
        // 第一列显示行号（留空）
        if (index === 0) {
          sums[index] = '';
          return;
        }

        // 第二列（剂量单位）显示"合计"文字
        if (index === 1) {
          sums[index] = '合计';
          return;
        }

        // 只处理需要计算的字段
        if (calcFields[column.property]) {
          const total = data.reduce((sum, item) => {
            const value = parseFloat(item[column.property]) || 0;
            return sum + value;
          }, 0);

          // 如果是cnt列，显示为整数，否则保留两位小数
          sums[index] = column.property === 'cnt'
              ? Math.round(total).toString()
              : total.toFixed(2);
        } else {
          // 其他列显示占位符（与图片中的"一"一致）
          sums[index] = '';
        }
      });

      return sums;
    },
    //左表格数据单击事件
    async handleCurrentRow(row) {
      try {
        const res = await getChargeDetail(row.id);
        this.tableData2 = [];
        this.tableData2 = res.data.feeListdetails.map(item => {
          if ([5, 6].includes(Number(item.feeType))) return item;
          const matchedOption = this.feeTypeOption1.find(
              option => option.id === Number(item.feeType)
          );
          return matchedOption
              ? {...item, feeTypeName: matchedOption.label}
              : item;
        });
        this.currentRowData = {};
        this.currentRowData = JSON.parse(JSON.stringify(row));
        this.currentRightRowData = JSON.parse(JSON.stringify(this.tableData2));
      } catch (error) {
        console.log(error);
        this.$message.error("系统异常:请联系管理员")
      } finally {

      }

    },

    //项目价格下拉框
    async getChargingPrice() {
      if (this.chargingPriceOptions.length > 0) return;
      const res = await getChargingPrice();
      this.chargingPriceOptions = res.data.map(item => {
        return {
          id: item.id, label: item.costname, odcost: item.odcost,
          executedepid: item.executedepid, depexecutetype: item.depexecutetype
        }
      })
    },

    //医生下拉框
    async getDoctorList() {
      if (this.doctorOptions.length > 0) return;
      const res = await getDoctorList()
      this.doctorOptions = res.data.map(item => {
        return {id: item.id, label: item.fullName}
      })
    },

    //根据身份证生日
    certnoMonitor(val) {
      if (!val.certno) return;

      const idCard18Reg = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
      if (!idCard18Reg.test(val.certno)) {
        this.$message.error("身份证格式不正确");
      }

      const data = this.getAgeAndMonthsFromIdCard(val.certno);
      val.ageYear = data.years;
      val.ageMonth = data.months;
      val.brdy = val.certno.slice(6, 10) + '-' +
          val.certno.slice(10, 12) + '-' +
          val.certno.slice(12, 14)
    },

    //根据身份证出生日期
    getAgeAndMonthsFromIdCard(idCard) {
      if (!idCard || idCard.length !== 18) return {years: 0, months: 0, birthday: ''};

      const birthStr = idCard.slice(6, 14); // 格式：YYYYMMDD
      const birthday = `${birthStr.slice(0, 4)}-${birthStr.slice(4, 6)}-${birthStr.slice(6, 8)}`;

      const birthDate = new Date(birthday);
      if (isNaN(birthDate.getTime())) return {
        years: 0,
        months: 0,
        birthday: ''
      };

      // 2. 获取当前日期
      const today = new Date();

      // 3. 计算周岁
      let years = today.getFullYear() - birthDate.getFullYear();

      // 4. 计算月龄（总月数差）
      let months = (today.getFullYear() - birthDate.getFullYear()) * 12 +
          (today.getMonth() - birthDate.getMonth());

      // 5. 调整年龄和月龄（如果生日未到）
      if (
          today.getMonth() < birthDate.getMonth() ||
          (today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
      ) {
        years--;
        months--;
      }

      // 6. 确保月龄为正数
      months = Math.max(0, months % 12); // 超过12个月的部分已计入周岁

      return {years, months, birthday};
    },

    //快速建档新增
    async handleAddCelerityFiling() {
      this.celerityFilingForm.tel = this.celerityFilingForm.conerTel;
      this.celerityFilingForm.restAddCode = this.handleAddressChangeCode(this.celerityFilingForm)
      this.celerityFilingForm.naplAddCode = this.handleAddressChangeCode(this.celerityFilingForm)
      console.log(this.celerityFilingForm)
      const res = await addDocphr(this.celerityFilingForm);
      if (res.code === 200) {
        this.celerityFilingDialogVisible = false;
      } else {
        this.$message.error(res.message)
      }

    },

    //转换城市代码
    handleAddressChangeCode(form) {
      const {province, city, county, town, village} = form;

      // 从村级开始逐级向上检查
      if (village && village.trim() !== '') {
        return village; // 返回村级代码
      }
      if (town && town.trim() !== '') {
        return town; // 返回乡级代码
      }
      if (county && county.trim() !== '') {
        return county; // 返回县级代码
      }
      if (city && city.trim() !== '') {
        return city; // 返回市级代码
      }
      return province || ''; // 默认返回省级（即使为空）
    },

    //科室下拉框
    async getDeptList() {
      if (this.deptOptions.length > 0) return;
      const res = await getDeptList();
      this.deptOptions = res.data.map(item => {
        return {id: item.id, label: item.deptName}
      })
    },

    //合约单位名称转拼音
    handleNameChangeCode(v, i) {
      switch (i) {
        case 3 :
          this.addUnitForm.pyCode =
              pinyin(this.addUnitForm.name, {pattern: 'first', toneType: 'none', separator: ''}).toLocaleUpperCase();
          break;
      }
    },

    //新增修改合约单位
    async handleAddContractUnit() {
      if (this.addUnitForm.id) {
        const res = await editContractUnit(this.addUnitForm);
        if (res.code === 200) {
        } else {
          this.$message.error("系统异常:修改合约单位失败!")
        }
      } else {
        const res = await addContractUnit(this.addUnitForm);
        if (res.code === 200) {
        } else {
          this.$message.error("系统异常:添加合约单位失败!")
        }
      }
      this.addUnitForm = {};
      this.addUnitForm.untAtte = 3;
      this.addUnitForm.state = 1;
      this.addUnitForm.area = 1;
      this.addUnitModalVisible = false;
    },

    //合约单位模态框清理
    handleCancelContract() {
      this.addUnitForm = {};
      this.addUnitForm.untAtte = 3;
      this.addUnitForm.state = 1;
      this.addUnitForm.area = 1;
      this.addUnitModalVisible = false;
    },

    //修改合约单位
    async handleEditContractUnit(item) {
      const res = await getContractUnit(item.id.toString())
      this.addUnitForm = res.data
      this.addUnitModalVisible = true;
    },

    //患者选择表格存储选中行对象
    handleClickRow(row) {
      this.patientChooseForm = row;
    },


    //患者搜索
    async handleSearch() {
      await this.handleConditionQuery();
    },

    //数据字典
    async dict() {
      const res = await dict();
      this.nationOption = res.data.natyEntities.map(item => {
        return {id: item.id, label: item.name}
      })
      this.certypeOption = res.data.certypeEntities.map(item => {
        return {id: item.id, label: item.name}
      })

      this.profttlOption = res.data.profttlEntities.map(item => {
        return {id: item.id, label: item.name}
      })

      this.prhCostOption = res.data.prhCostType.map(item => {
        return {id: item.id, label: item.name}
      })

      this.prhTypeOption = res.data.prhType.map(item => {
        return {id: item.id, label: item.name}
      })

      this.rltsEntitiesOption = res.data.rltsEntities.map(item => {
        return {id: item.id, label: item.name}
      })

      this.untAtteOption = res.data.unatteVo.map(item => {
        return {id: item.id, label: item.name}
      })

      this.ntlyOptions = res.data.country.map(item => {
        return {id: item.id, label: item.name}
      })

      this.chinaMakeOptions = res.data.methodTypeVO.map(item => {
        return {id: item.id, label: item.name}
      })

      this.tcmwayOptions = res.data.tcmway.map(item => {
        return {id: item.id, label: item.name}
      })
    },

    //递级清理地域数据, 如(清空市数据,则会清空市下面所有下拉框数据(县-镇-村-乡))
    handleClear(res) {
      switch (res) {
        case 1:
          this.patientForm.province = ''
          this.patientForm.city = ''
          this.patientForm.county = ''
          this.patientForm.town = ''
          this.patientForm.village = ''
          this.villageOption = [];
          this.townOption = [];
          this.countyOption = [];
          this.cityOption = [];
          this.profttlOption = [];
          break;

        case 2:
          this.patientForm.city = ''
          this.patientForm.county = ''
          this.patientForm.town = ''
          this.patientForm.village = ''
          this.villageOption = [];
          this.townOption = [];
          this.countyOption = [];
          this.cityOption = [];
          break;
        case 3:
          this.patientForm.county = '';
          this.patientForm.town = '';
          this.patientForm.village = '';
          this.villageOption = [];
          this.townOption = [];
          this.countyOption = [];
          break;

        case 4:
          this.patientForm.town = '';
          this.patientForm.village = '';
          this.villageOption = [];
          this.townOption = [];
          break;

        case 5:
          this.patientForm.village = '';
          this.villageOption = [];
          break;
      }
    },

    //合约单位下拉框
    async getContuntList() {
      const res = await getContuntList();
      this.contractUnitOption = res.data.map(item => {
        return {id: item.id, label: item.name}
      })
      const finallyContunt = res.data[res.data.length - 1];
      this.addUnitForm.code = parseInt(finallyContunt.code) + 1;
    },

    //获取村
    async getVillage() {
      const areaCode = this.patientForm.town === '' ? this.celerityFilingForm.town : this.patientForm.town;
      const res = await getArea({areaCode: areaCode, areaLevel: 5, condtion: 'area_t_code'})
      this.villageOption = res.data.map(item => {
        return {
          id: item.areaCode, label: item.areaName, areaLevel: item.areaLevel
        }
      })
    },
    //获取镇
    async getTown() {
      this.patientForm.village = ''
      this.celerityFilingForm.village = ''
      const areaCode = this.patientForm.county === '' ? this.celerityFilingForm.county : this.patientForm.county;
      const res = await getArea({areaCode: areaCode, areaLevel: 4, condtion: 'area_d_code'})
      this.townOption = res.data.map(item => {
        return {
          id: item.areaCode, label: item.areaName, areaLevel: item.areaLevel
        }
      })
    },
    //获取县
    async getCounty() {
      this.patientForm.town = ''
      this.patientForm.village = ''
      this.celerityFilingForm.town = ''
      this.celerityFilingForm.village = ''
      const areaCode = this.patientForm.city === '' ? this.celerityFilingForm.city : this.patientForm.city;
      const res = await getArea({areaCode: areaCode, areaLevel: 3, condtion: 'area_c_code'})
      this.countyOption = res.data.map(item => {
        return {
          id: item.areaCode, label: item.areaName, areaLevel: item.areaLevel
        }
      })
    },
    //获取市
    async getCity() {
      this.patientForm.county = ''
      this.patientForm.town = ''
      this.patientForm.village = ''
      this.celerityFilingForm.county = ''
      this.celerityFilingForm.town = ''
      this.celerityFilingForm.village = ''
      const areaCode = this.patientForm.province === '' ? this.celerityFilingForm.province : this.patientForm.province;
      const res = await getArea({areaCode: areaCode, areaLevel: 2, condtion: 'area_p_code'})
      this.cityOption = res.data.map(item => {
        return {
          id: item.areaCode, label: item.areaName, areaLevel: item.areaLevel
        }
      })
    },
    //获取省
    async getArea() {
      this.patientForm.city = ''
      this.patientForm.county = ''
      this.patientForm.town = ''
      this.patientForm.village = ''
      this.celerityFilingForm.city = ''
      this.celerityFilingForm.county = ''
      this.celerityFilingForm.town = ''
      this.celerityFilingForm.village = ''
      const res = await getArea();
      this.provinces = res.data.map(item => {
        return {id: item.areaCode, label: item.areaName, areaLevel: item.areaLevel}
      })
    },

    //自动计算宽度
    columnWidth(col, list) {
      let prop = col.prop, lab = col.lab;
      let width = 100; // 设定一个最小值
      let maxlenStr = ""; // 最长字符串


      for (let info of list) {
        if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
      }
      width = Math.max(width, len(lab), len(maxlenStr));
      // 表格自带的内边距(20px) 自调
      return width + 8; // 这里加了 12px
      function len(str) {
        // 实际分配长度可根据需要自行调整
        let length = 12;
        for (const char of str + "") {
          // 英文小写字符 8px
          if ("a" <= char && char <= "z") length += 8;
          // 英文大写字符 8px
          else if ("A" <= char && char <= "Z") length += 8;
          // 中文字符 28px
          else if (char >= "\u4e00" && char <= "\u9fa5") length += 12;
          // 其他 8px
          else length += 12;
        }
        return length;
      }
    },

    // 实时宽度
    updateWindowWidth() {
      this.windowWidth = window.innerWidth - 288;
    },

    //表格数据回显
    safeGetMappedValue(col, row) {
      // 1. 检查数据有效性
      const rawValue = row[col.prop];
      if (rawValue === null || rawValue === undefined) return ' ';

      // 2. 检查映射数组
      const mapArray = this[col.op];
      if (!col.op || !Array.isArray(mapArray)) return rawValue;

      // 3. 执行映射
      const matched = mapArray.find(item => item.id == rawValue);
      return matched?.label || rawValue;
    },

    getColumnWidth(label, prop, tableData) {
      const minWidth = 80;
      const padding = 30; // 增加边距缓冲
      const contentList = tableData.map(item => item?.[prop] ?? '');

      // 计算所有内容宽度（包括表头）
      const widths = [...contentList, label].map(text => {
        const str = String(text || '');
        return this.getTextWidth(str) + padding;
      });

      return Math.max(minWidth, ...widths);
    },

    // 精确计算文本宽度（使用Canvas）
    getTextWidth(text, fontSize = 14) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.font = `${fontSize}px Microsoft YaHei`;
      return ctx.measureText(text).width;
    },

    labelHead(h, {column, $index}) {
      let l = column.label.length;
      let f = 12;
      column.minWidth = f * (l + 5); //加上一个文字长度
      return h("div", {class: "table-head", style: {width: "100%"}}, [
        column.label,
      ]);
    },
    handleSizeChange(val) {
      this.pageNum = val;
      this.loadData();
    },
    //当前条数改变触发
    handleCurrentChange(val) {
      this.pageNum = val;
      this.loadData();
    },
  }
}
</script>


<style lang="less" scoped>
/* 响应式表单样式 */
.responsive-form {
  overflow: hidden;
}

/* 表单行样式 */
.form-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: -8px; /* 补偿 gutter 的 margin */
}

/* 通用输入控件样式 */
.full-width-input,
.full-width-select,
.full-width-date-picker {
  width: 100% !important;
}

/* 时间范围容器 */
.date-range-container {
  display: flex;
  align-items: center;
  width: 100%;
}

/* 日期选择器 */
.date-picker {
  flex: 1;
  min-width: 150px;
}

/* 日期分隔符 */
.date-separator {
  margin: 0 8px;
  color: #999;
}

.dual-table-container {
  display: flex;
  height: 60vh; /* Adjust height as needed */
}

.table-wrapper {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.patient-dialog {
  display: flex;
  justify-content: center;
  align-items: Center;
  overflow: auto;

  .el-dialog {
    margin: 0 auto !important;
    position: relative;

    .el-dialog__header {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      width: 100%;
      height: 60px;
      z-index: 1;
    }

    .el-dialog__body {
      width: 100%;
      overflow: hidden;
      overflow-y: auto;
      max-height: 80vh; //最大高度为视口高度的90%
      padding-top: 80px;
      padding-bottom: 100px;
      z-index: 1;
    }

    .el-dialog__footer {
      position: absolute;
      left: 0;
      bottom: 0;
      right: 0;
      width: 100%;
      height: 80px;
      z-index: 1;
    }
  }
}

/* 冲销状态标签样式 */
.nuy-state-tag {
  margin: 2px;
  font-weight: 500;
  display: inline-flex;
  align-items: center;
}

.nuy-state-0 {
  color: #67c23a;
  background-color: #f0f9eb;
  border-color: #e1f3d8;
}

.nuy-state-1 {
  color: #e6a23c;
  background-color: #fdf6ec;
  border-color: #faecd8;
}

.nuy-state-2 {
  color: #f56c6c;
  background-color: #fef0f0;
  border-color: #fde2e2;
}

/* 图标样式 */
.el-icon-check {
  margin-right: 5px;
  color: #67c23a;
}

.el-icon-refresh {
  margin-right: 5px;
  color: #e6a23c;
}

.el-icon-close {
  margin-right: 5px;
  color: #f56c6c;
}

.compact-form-box {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 12px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-row {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.time-range {
  display: flex;
  align-items: center;
}

.time-range .el-time-picker {
  flex: 1;
}

.separator {
  margin: 0 8px;
  color: #606266;
}

.el-form-item {
  margin-bottom: 0;
}


.payment-form {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 4px;
}

.form-header {
  background: #409EFF;
  color: white;
  padding: 10px 15px;
  margin: -20px -20px 20px -20px;
  border-radius: 4px 4px 0 0;
  font-size: 16px;
  font-weight: bold;
}

.form-section {
  background: white;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.payment-summary {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  margin-top: 15px;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
  display: inline-block;
  width: 120px;
  text-align: left;
}

.form-actions {
  text-align: center;
  margin-top: 20px;
}


.el-table__footer-wrapper {
  position: sticky !important;
  bottom: 0;
  background: white;
  display: table-footer-group !important;
}

/* 调整滚动区域 */
.el-table__body-wrapper {
  max-height: calc(55vh - 48px) !important;
  overflow-y: hidden !important;
}

.custom-summary-table {
  overflow: visible !important;
}

/* 将合计行固定在表格数据下方（不受滚动条影响） */
.custom-summary-table .el-table__footer-wrapper {
  overflow: visible !important;
  position: sticky !important;
  bottom: 0;
  background: white;
  z-index: 10;
  border-top: 1px solid #ebeef5; /* 可选：添加分隔线 */
}

/* 调整表格内滚动区域高度 */
.custom-summary-table .el-table__body-wrapper {
  max-height: calc(55vh - 48px); /* 减去合计行高度 */
  overflow-y: auto !important;
}

/* 全局样式或组件内样式 */
.el-table__footer {
  background-color: white !important; /* 改为白色背景 */
  border-top: 1px solid #EBEEF5; /* 保留顶部边框线 */
}

.el-table__footer .el-table__cell {
  background-color: inherit !important; /* 继承白色背景 */
}

/* 调整文字样式（可选） */
.el-table__footer .cell {
  color: #606266; /* 默认文字颜色 */
}

.medical-system-container {
  display: flex;
  flex-direction: column;
  height: 65vh;
  width: 100%;
  overflow: hidden;
  position: relative;
}

/* 主表格区域 */
.table-main-container {
  display: flex;
  flex: 1;
  position: relative;
  overflow: auto;
  transition: all 0.3s ease;
}

/* 左表格 - 默认铺满 */
.table-left {
  flex: 1 1 100%;
  height: 100%;
  overflow: auto;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  min-width: 0; /* 防止内容溢出 */
}

/* 右抽屉表格 - 初始隐藏 */
.table-drawer {
  flex: 0 0 auto;
  height: 100%;
  width: 0;
  background: #fff;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  z-index: 10;
  overflow: hidden;
}

/* 抽屉打开状态 */
.table-drawer.open {
  flex: 0 0 40%; /* 固定宽度 */
  min-width: 400px;
}

.drawer-content {
  height: 100%;
  width: 100%;
  overflow: auto;
  box-sizing: border-box;
}

/* 当抽屉打开时，左表格缩进 */
.table-main-container.with-drawer .table-left {
  flex: 1 1 60%; /* 剩余空间 */
}

/* 底部控制表单 - 固定在底部 */
.bottom-control-form {
  padding: 1px;
  background: #f5f7fa;
  border-top: 1px solid #e6e6e6;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.05);
}

.form-grid {
  display: flex;
  flex-direction: column;
}

.form-main {
  margin-bottom: 10px;
}

/* 按钮组布局 */
.button-group {
  display: flex;
  justify-content: space-between;
}

.primary-actions {
  display: flex;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

/* 表格样式增强 */
.el-table {
  height: 100%;
  width: 100%;
  display: flex !important;
  flex-direction: column;
}

.el-table th {
  background-color: #f8f8f9;
  font-weight: 600;
}

.el-table--border {
  border: 1px solid #ebeef5;
}

@media (max-width: 1200px) {
  .table-drawer.open {
    width: 50%;
    min-width: 350px;
  }

  .table-main-container.with-drawer .table-left {
    margin-right: 50%;
  }
}

.form-grid {
  display: flex;
  flex-direction: column;
}

.form-main {
  margin-bottom: 10px;
}

.button-group {
  display: flex;
  justify-content: space-between;
}

.primary-actions,
.action-buttons {
  display: flex;
  gap: 8px;
}


.button-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px; /* 按钮间距 */
}


/* 新增底部输入盒子样式 */
.bottom-input-box {
  padding: 15px;
  background: #f8f8f9;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
}


/deep/ .el-dialog__header {
  padding: 18px;
  background-color: #007bb0;
}

/deep/ .el-dialog__title {
  font-size: 18px;
  color: #fff;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

/deep/ .el-input.is-disabled .el-input__inner {
  color: #87898f;
}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  color: #87898f;
}

.dialog {
  .addUnitDialog {
    .tabs {
      /deep/ .el-select > .el-input {
        width: 172px;
      }

      /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 172px;
      }

      /deep/ .el-form-item__content {
        display: flex;

        span {
          font-size: 12px;
        }
      }

      .oneLine {
        width: 524px;
        // background-color: indianred;
      }
    }

    /deep/ .el-dialog__title {
      font-size: 15px;
    }

    /deep/ .el-table {
      font-size: 15px;
    }
  }

  .patient-dialog {
    .tabs {
      /deep/ .el-select > .el-input {
        width: 172px;
      }

      /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 172px;
      }

      /deep/ .el-form-item__content {
        display: flex;

        span {
          font-size: 12px;
        }
      }

      .oneLine {
        width: 524px;
        // background-color: indianred;
      }
    }

    /deep/ .el-dialog__title {
      font-size: 15px;
    }

    /deep/ .el-table {
      font-size: 15px;
    }
  }
}


/* Vue 2 深度选择器写法 */
.custom-table /deep/ .el-table--border {
  border: 1px solid #e6e6e6;
}

.custom-table /deep/ .el-table__header th,
.custom-table /deep/ .el-table__body td {
  border-right: 1px solid #e6e6e6;
  border-bottom: 1px solid #e6e6e6;
}

.custom-table /deep/ .el-table__header th {
  background-color: #f5f7fa; /* 表头背景色 */
}

.data-row {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.label {
  width: 70px;
  font-size: 13px;
}

.el-input {
  flex: 1;
}


.side-panel {
  width: 240px;
  padding: 10px;
  background: #f5f7fa;
}

.registration-box {
  background: white;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.data-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.label {
  width: 70px;
  font-size: 13px;
  color: #ffffff;
  margin-right: 4px;
}

.el-input {
  flex: 1;
}

.el-input.is-disabled .el-input__inner {
  background-color: #f5f5f5;
  color: #666;
}

/* 新增样式 */
.register-group {
  width: 50%;
  display: flex;
  gap: 16px;
  margin-top: 8px;
}

/* 调整原有分隔线位置 */
.divider-line {
  width: 100%;
  margin: 12px 0 8px;
}

/* 强制同行显示 */
.register-type + .clinic-room {
  margin-left: -8px; /* 补偿间距 */
}

/* 关键修复样式 */
.compact-form {
  /* 在原有样式基础上添加 */

  .register-type,
  .clinic-room {
    flex: 1; /* 平分剩余空间 */
    min-width: 240px; /* 最小宽度保证换行后对齐 */
    max-width: 50%; /* 最大不超过50% */

    /deep/ .el-form-item__content {
      width: calc(100% - 90px) !important; /* 匹配label宽度 */
    }
  }

  /* 强制同行显示 */

  .register-type + .clinic-room {
    margin-left: -8px; /* 补偿间距 */
  }

  /deep/ .el-form-item__content {
    margin-left: 0 !important; /* 消除ElementUI默认的左侧间距 */
    width: auto !important; /* 取消固定宽度 */
  }

  /deep/ .el-form-item__label {
    padding-right: 6px !important; /* 标签与输入框间距 */
    width: auto !important; /* 取消标签固定宽度 */
    flex: none !important; /* 禁用flex自动分配 */
  }

  .el-form-item {
    /* 调整整体间距 */
    gap: 4px; /* 标签与控件间距 */
    margin-bottom: 15px;
    /* 微调对齐方式 */
    align-items: baseline;
  }

  /* 特殊处理复选框 */

  .el-checkbox {
    margin-left: 2px;

    /deep/ .el-checkbox__label {
      display: none; /* 隐藏默认标签 */
    }
  }

  /* 输入框尺寸补偿 */

  .el-input--mini {
    line-height: 28px;

    /deep/ .el-input__inner {
      padding: 0 8px;
    }
  }
}

.compact-form-box {
  height: auto !important; /* 改为自适应高度 */
  padding: 12px 8px; /* 调整内边距 */
}

.compact-form {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 16px; /* 行列间距 */

  .el-form-item {
    margin: 0;
    display: inline-flex;
    align-items: center;

    /* 标签对齐 */

    /deep/ .el-form-item__label {
      line-height: 28px;
      padding-right: 4px;
    }

    /* 表单控件通用样式 */

    .el-input,
    .el-select,
    .el-date-editor {
      width: 100px; /* 默认宽度 */
    }

    /* 特定字段宽度调整 */

    &[label="性别:"] .el-select {
      width: 70px;
    }


    &[label="职业:"] .el-select {
      width: 130px;
    }

    &[label="病员费别:"] .el-select,
    &[label="病员类型:"] .el-select {
      width: 135px;
    }

    &[label="联系电话:"] .el-input {
      width: 135px;
    }


    &[label="挂号类别:"] .el-select,
    &[label="诊室:"] .el-select {
      width: 300px;
    }

    /* 地址输入组 */

    .age-select-address {
      display: flex;
      align-items: center;
      gap: 4px;

      .el-input {
        width: 60px !important;

        &:nth-last-child(2) {
          width: 150px !important;
        }

        /* 乡镇输入框 */
      }
    }
  }

  /* 分隔线样式 */

  .divider-line {
    width: 100%;
    margin: 20px 10px 0;
    border-top: 1px solid #ebeef5;
  }
}


.divider-line {
  height: 1px;
  background-color: #ebeef5;
  margin: 15px 10px 0;
}

.compact-form-box {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 3px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.compact-form {
  font-size: 12px;
}

.el-form-item {
  margin-bottom: 5px;
}

.age-unit {
  margin: 0 5px;
  color: #ffffff;
  font-size: 12px;
}

.MedicenCata {
  height: 100%;
  width: 100%;

  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 40px;
    background-color: #efefef;
    padding: 4px;

    .header-icon {
      width: 100%;
      display: flex;
      align-items: center;
    }
  }

}
</style>